import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { CacheService } from './../../services/cache.service';
import { NetService } from './../../services/net.service';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.scss']
})
export class UserListComponent implements OnInit {
  public headers = ['用户名', '昵称', '角色', '操作'];
  public dataSet = [];
  public modalVisible = false;
  public userForm: FormGroup;
  public roleList = [];
  constructor(
    private cacheService: CacheService,
    private fb: FormBuilder,
    private net: NetService,
    private nzmsg: NzMessageService
  ) { }

  async addUser() {
    this.userForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      nickName: [null],
      role: [null, [Validators.required]],
      email: [null, [Validators.email]]
    });
    const roles = await this.net.get('/api/roles');
    if (roles) {
      this.roleList = roles['data'];
    }
    this.modalVisible = true;
  }

  modalOk(): void {
    Object.keys(this.userForm.controls).forEach(item => {
      this.userForm.controls[item].markAsDirty();
      this.userForm.controls[item].updateValueAndValidity();
    });
    if (this.userForm.valid) {
      this.modalVisible = false;
      this.submitForm();
    }
  }
  async submitForm() {
    const result = await this.net.post('/api/users-admin', this.userForm.value);
    if (result) {
      this.nzmsg.success('创建用户成功！');
      this.getUserList();
    }
  }
  async getUserList() {
    const result = await this.net.get('/api/users');
    if (result) {
      this.dataSet = result['data'];
    }
  }
  modalCancel(): void {
    this.modalVisible = false;
  }
  async delUser(item) {
    const result = await this.net.delete(`/api/users/${item._id}`);
    if (result) {
      this.getUserList();
      this.nzmsg.success('删除用户成功!');
    }
  }

  async ngOnInit() {
    this.userForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      nickName: [null],
      role: [null, [Validators.required]],
      email: [null, [Validators.email]]
    });
    const users = await this.net.get('/api/users');
    if (users) {
      this.dataSet = users['data'];
    }
  }
}
